//
//  TrackUploadService.swift
//  mggz
//
//  Created by ShareAnimation on 2017/11/16.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import CoreLocation
import ObjectMapper
class TrackUploadService: NSObject {
    static let sharedInstance = TrackUploadService()
    fileprivate override init() {
        super.init()
        self.userAdress = ""
        locationService.delegate = self
        self.geoSearch.delegate = self
        self.locationService.allowsBackgroundLocationUpdates = true //允许后天定位
        self.locationService.pausesLocationUpdatesAutomatically = false//不允许系统停止定位，否则20分后就会停止
        let locationManger = self.locationService.value(forKey: "locationManager") as? CLLocationManager
        if locationManger != nil {
            locationManger?.allowsBackgroundLocationUpdates = true
            locationManger?.pausesLocationUpdatesAutomatically = false
            locationManger?.requestAlwaysAuthorization()
            locationManger?.requestWhenInUseAuthorization()
            locationManger?.startUpdatingLocation()
        }
        mwLocationManager.allowsBackgroundLocationUpdates = true
        mwLocationManager.pausesLocationUpdatesAutomatically = false
        mwLocationManager.requestAlwaysAuthorization()
        mwLocationManager.requestWhenInUseAuthorization()
        mwLocationManager.startUpdatingLocation()
    }
    
    //MARK:定位服务
    fileprivate let mwLocationManager = CLLocationManager()
    fileprivate let locationService = BMKLocationService()
    fileprivate let geoSearch = BMKGeoCodeSearch()
     var userAdress:String?
    func start() {
        if self.isActive != true {
            self.lastDate = Date()
            self.isActive = true
            self.startLocation()
            
        }
        else {
            
        }
    }
    
    func stop() {
        self.isActive = false
    }
    func stopBackGroundLocation(){
        self.locationService.stopUserLocationService()
        mwLocationManager.stopUpdatingLocation()
        mwLocationManager.allowsBackgroundLocationUpdates = false
    }
    func startLocation() {
        self.locationService.stopUserLocationService()
        self.locationService.startUserLocationService()
    }
    //MARK:轨迹服务
    
    /// 轨迹上传服务是否启动。true表示启动
    private(set) var isActive: Bool = false
    
    fileprivate var lastDate:Date! //上一次上传轨迹的时间点·
    
    //连点是否在指定范围内
    var twoPointWithinTheSpecifiedRange:((Bool) -> Void)?
    fileprivate lazy var fenceList : [SignedDataModel] = [SignedDataModel]()
    fileprivate lazy var signedPointList : [SignedDataModel] = [SignedDataModel]()
    var recordPolicyModel: RecordPolicy!
    var demandBaseMigrantWorkerId : String!
    //给轨迹上传服务匹配策略。切换项目或者刷新的时候要重新匹配
    func add(_ recordPolicy: RecordPolicy, demandBaseMigrantWorkerId: String) {
        
        self.recordPolicyModel = recordPolicy
        self.demandBaseMigrantWorkerId = demandBaseMigrantWorkerId
        
        self.startLocation()
    }
    //根据策略的时间决定是否允许上传。true表示是
    fileprivate  func canUpload() -> Bool {
        let currentInterval = fabs(Date().timeIntervalSince(self.lastDate!))
        
        var preferredInterval : TimeInterval!
        if let rate = recordPolicyModel.locationRate, let rateInt = Int(rate) {
            preferredInterval = TimeInterval.init(rateInt * 60)
        }
        else {
            preferredInterval = TimeInterval.init(15 * 60)
        }
        //        //测试，默认5分钟上传一次
        //                preferredInterval = 10
        print("打印当期的时间")
        print(currentInterval)
        print(preferredInterval)
        if currentInterval >= preferredInterval {
            self.lastDate = Date()
            return true
        }
        return false
    }
    
    //上传到服务器
    fileprivate func uploadRecordTrack(_ longitude: String, latitude: String, isException: Bool) {
        var guid: String?
        let dispatchGroup = DispatchGroup()
        dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else {
                WWError(response.message)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.notify(queue: DispatchQueue.main) {
            guard guid != nil else {
                return
            }
            RecordTrack.uploadRecordTrack(guid!, demandBaseMigrantWorkerID: self.demandBaseMigrantWorkerId, isException: isException, longitude: longitude, latitude: latitude, userAdress:self.userAdress!){(response) in
                if response.success {
                    print("轨迹上传成功")
                }
                else {
                    
                }
            }
        }
    }
}

extension TrackUploadService: BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate {
    
    func didUpdate(_ userLocation: BMKUserLocation!) {
        let coordinate = userLocation.location.coordinate
        let lon = coordinate.longitude
        let lat = coordinate.latitude
        let reverseGeocodeSearchOption = BMKReverseGeoCodeOption()
        reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate
        let flag = geoSearch.reverseGeoCode(reverseGeocodeSearchOption)
        if flag {
            
        } else {
            
        }
        //print(self.recordPolicyModel.electricFenceList)
        guard let fenceList = self.recordPolicyModel?.electricFenceList  else {
            return
        }
        guard let signedList = self.recordPolicyModel?.signedPointList else {
            return
        }
        self.fenceList = Mapper<SignedDataModel>().mapArray(JSONObject: fenceList)!
        self.signedPointList = Mapper<SignedDataModel>().mapArray(JSONObject: signedList)!
        
        var signedCoorArr = [CLLocationCoordinate2D]()
        for (index1,value2) in self.signedPointList.enumerated() {
            if let lat = value2.Latitude, let lon = value2.Longitude {
                if let doubuleLat = Double(lat), let doubleLon = Double(lon) {
                    var coor = CLLocationCoordinate2D()
                    coor.latitude = doubuleLat
                    coor.longitude = doubleLon
                    signedCoorArr.append(coor)
                }
            }
        }
        
        var signF:Int? = 0
        if signedCoorArr.count>0{
            for (index,value) in signedCoorArr.enumerated(){
                if BMKCircleContainsCoordinate(coordinate, value, Double(self.recordPolicyModel.signedRange!)!) == true{
                    signF = signF!+1
                }
            }
            if signF == 0{
                if let closure = self.twoPointWithinTheSpecifiedRange {
                    closure(false)
                    LoginAuthenticationService.setupIsRangeData(range: "2")
                }
            }else{
                if let closure = self.twoPointWithinTheSpecifiedRange {
                    closure(true)
                    LoginAuthenticationService.setupIsRangeData(range: "1")
                }
            }
        }
        
        var fenceCoorArr = [CLLocationCoordinate2D]()
        for (index,value) in self.fenceList.enumerated() {
            if let lat = value.Latitude, let lon = value.Longitude {
                if let doubuleLat = Double(lat), let doubleLon = Double(lon) {
                    var coor = CLLocationCoordinate2D()
                    coor.latitude = doubuleLat
                    coor.longitude = doubleLon
                    fenceCoorArr.append(coor)
                }
            }
        }
        let userRange = BMKPolygonContainsCoordinate(coordinate, &fenceCoorArr, UInt(fenceCoorArr.count))
        
        //定位是一致开着的，但是轨迹上传是根据策略来的
        if canUpload() {
            self.uploadRecordTrack("\(lon)", latitude: "\(lat)",isException: !userRange)
        }
    }
    func didFailToLocateUserWithError(_ error: Error!) {
        
        
    }
    func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        if error == BMK_SEARCH_NO_ERROR {
            guard let firstAdress = result.address,let secondAdress = result.sematicDescription else{
                self.userAdress = result.address
                return
            }
            
            self.userAdress = firstAdress + secondAdress
            
        }
    }
}













